
class TreeNode {
    val: number
    left: TreeNode | null
    right: TreeNode | null
    constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
        this.val = (val===undefined ? 0 : val)
        this.left = (left===undefined ? null : left)
        this.right = (right===undefined ? null : right)
    }
}
 

 function addOneRow(root: TreeNode | null, val: number, depth: number): TreeNode | null {
    if (depth === 1) {
        const newRoot: TreeNode = new TreeNode(val,root,null)
        return newRoot
    }else {
        findDepth(root,val,depth-1)
    }
    return root
};

function findDepth(root: TreeNode | null, val: number, depth: number): void{
    if (depth === 1) {
        (root as TreeNode).left  = new TreeNode(val,root?.left,null);
        (root as TreeNode).right  = new TreeNode(val,null,root?.right)
    }else if(root?.left && root?.right){
        findDepth(root.left,val,depth-1)
        findDepth(root.right,val,depth-1)
    }else if(root?.left){
        findDepth(root.left,val,depth-1)
    }else if(root?.right){
        findDepth(root.right,val,depth-1)
    }
}

const val: number = 1
const depth: number = 3
const t5 = new TreeNode(5,null,null)
const t3 = new TreeNode(3,null,null)
const t1 = new TreeNode(1,null,null)
const t2 = new TreeNode(2,t3,t1)
const t6 = new TreeNode(6,t5,null)
const root = new TreeNode(4,t2,t6)

console.log(addOneRow(root,val,depth))